package per.vic.attachment.web;

/**
 * 描述:
 * @author Vic.xu
 * @date 2022-01-14 9:39
 */

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import per.vic.attachment.autoconfigure.AttachmentProperties;
import pers.vic.boot.base.model.BaseResponse;
import pers.vic.boot.base.tool.Tools;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**服务端接口的拦截器 检验客户端合法性 */
public class AttachmentClientCheckInterceptor extends HandlerInterceptorAdapter {

    AttachmentProperties attachmentProperties;

    public AttachmentClientCheckInterceptor(AttachmentProperties attachmentProperties) {
        this.attachmentProperties = attachmentProperties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        String password = attachmentProperties.getPassword();
        if (StringUtils.isBlank(password)) {
            return true;
        }

        String header = request.getHeader(AttachmentProperties.HEADER_CHECK_NAME);
        if (!StringUtils.equals(password, header)) {
            Tools.writeJson(BaseResponse.error("不合法的请求"), response);
            return false;
        }
        return true;
    }


}
